package com.bwie.common.utils;

import java.util.*;

public class WeightedLottery {
    private Map<String, Integer> items; // 存储奖品和对应的权重

    public WeightedLottery() {
        items = new HashMap<>();
    }

    public void addItem(String item, int weight) {
        items.put(item, weight);
    }

    public String drawWinner() {
        int totalWeight = 0;
        for (int weight : items.values()) {
            totalWeight += weight;
        }

        int randomNum = new Random().nextInt(totalWeight) + 1;
        int cumulativeWeight = 0;

        for (Map.Entry<String, Integer> entry : items.entrySet()) {
            cumulativeWeight += entry.getValue();
            if (randomNum <= cumulativeWeight) {
                return entry.getKey(); // 返回中奖项
            }
        }

        return null; // 如果没有中奖项，返回null
    }

    public static void WeightedLottery(String[] args) {
        WeightedLottery lottery = new WeightedLottery();
        lottery.addItem("奖品1", 1); // 权重为1
        lottery.addItem("奖品2", 5); // 权重为5
        lottery.addItem("奖品3", 10); // 权重为10
        lottery.addItem("奖品4", 50); // 权重为50

        String winner = lottery.drawWinner();
        System.out.println("中奖项：" + winner);
    }
}